//
//  MoviePlaybackCache.m
//  Vgo
//
//  Created by 21CN Vgo on 10-9-20.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MoviePlaybackCache.h"
#import "CmnMacro.h"

@implementation MoviePlaybackCache

@synthesize dataPath;

static MoviePlaybackCache* _sharedMoviePlaybackCache; // self

#pragma mark singleton
- (id)init
{
    if(self = [super init])
	{
        dataPath = nil;
        dictCache = [[NSMutableDictionary alloc] init];
        [self initCache];
    }
	return self;
}

- (void)dealloc
{
	SAFE_RELEASE(dictCache);
	SAFE_RELEASE(dataPath);
	[super dealloc];
}

+ (MoviePlaybackCache *)sharedMoviePlaybackCache
{
	@synchronized(self)
	{
        if (_sharedMoviePlaybackCache == nil)
		{
            [[self alloc] init]; // assignment not done here
        }
    }
    return _sharedMoviePlaybackCache;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
	{
        if (_sharedMoviePlaybackCache == nil)
		{
            _sharedMoviePlaybackCache = [super allocWithZone:zone];			
            return _sharedMoviePlaybackCache;  // assignment and return on first allocation
        }
    }
	
    return nil; //on subsequent allocation attempts return nil	
}

- (id)copyWithZone:(NSZone *)zone
{
	return self;
}

- (id)retain
{
	return self;
}

- (unsigned)retainCount
{
	return UINT_MAX;  //denotes an object that cannot be released
}

- (oneway void)release
{
	//do nothing
}

- (id)autorelease
{
	return self;
}

#pragma mark member functions

- (NSString *)cacheFile:(NSURL *)theURL;
{
	NSString * filePath = [[theURL path] lastPathComponent];
	filePath = [dataPath stringByAppendingPathComponent:filePath];
	filePath = [filePath stringByAppendingString:@".cache"];
	
	return filePath;
}

- (void)cachePlaybackTime:(NSTimeInterval)time withURL:(NSURL *)theURL
{
	NSString * filePath = [self cacheFile:theURL];
	
	//NSLog(@"cachePlaybackTime %f file Path : %@", time, filePath);

	NSData * data = [NSData dataWithBytes:&time length:sizeof(time)];
	[data writeToFile:filePath atomically:TRUE];
	
	[dictCache setValue:data forKey:filePath];
}

- (NSTimeInterval)cachedPlaybackTimeWithURL:(NSURL *)theURL
{
	NSTimeInterval time = 0.0;
	
	NSString * filePath = [self cacheFile:theURL];
	
	NSData * data = [dictCache valueForKey:filePath];
	
	if (data == nil)
	{
		data = [NSData dataWithContentsOfFile:filePath];
		[dictCache setValue:data forKey:filePath];
	}
	
	if (data)
	{
		memcpy(&time, [data bytes], sizeof(time));
	}
	
	return time;
}

- (void) removeCache:(NSURL *)theURL
{
	NSError *error;
	NSString * filePath = [self cacheFile:theURL];

	[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
	
	[dictCache removeObjectForKey:filePath];
}

- (void) initCache
{
	/* create path to cache directory inside the application's Documents directory */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MoviePlaybackCache"];
	
	/* check for existence of cache directory */
	if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
		return;
	}
	
	NSError *error;
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath 
								   withIntermediateDirectories:YES
													attributes:nil 
														 error:&error]) {
		return;
	}
}


/* removes every file in the cache directory */

- (void) clearCache
{
	NSError *error;
	
	[dictCache removeAllObjects];
	
	/* remove the cache directory and its contents */
	if (![[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error]) {
		return;
	}
	
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath 
								   withIntermediateDirectories:YES
													attributes:nil 
														 error:&error]) {
		return;
	}
}

@end
